package com.jinke.api.modules.app.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.jinke.api.common.api.CommonPage;
import com.jinke.api.common.api.CommonResult;
import com.jinke.api.generator.GsonUtil;
import com.jinke.api.modules.app.enums.BalanceLogType;
import com.jinke.api.modules.app.enums.BalanceType;
import com.jinke.api.modules.app.enums.OrderStatus;
import com.jinke.api.modules.app.model.BalanceLog;
import com.jinke.api.modules.app.model.Order;
import com.jinke.api.modules.app.request.BalanceLogQueryRequest;
import com.jinke.api.modules.app.response.UmsBalanceLogExport;
import com.jinke.api.modules.app.service.BalanceLogService;
import com.jinke.api.modules.app.service.OrderService;
import com.jinke.api.modules.ums.model.UmsAdmin;
import com.jinke.api.modules.ums.service.UmsAdminService;
import com.jinke.api.modules.ums.vo.SimpleUser;
import com.jinke.api.security.util.AdminUserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.dreamlu.mica.core.utils.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author macro
 * @since 2024-01-13
 */
@RestController
@RequestMapping("/app/balance/log")
@Api(value = "资金明细", tags = "资金明细")
public class BalanceLogController {

    @Resource
    BalanceLogService balanceLogService;
    @Resource
    private StaticController staticController;
    @Resource
    private UmsAdminService umsAdminService;
    @Resource
    private OrderService orderService;

    @ApiOperation("用户资金明细查询")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<BalanceLog>> list(BalanceLogQueryRequest request) {
        request.setUserId(AdminUserUtil.getUserId().intValue());
        Page<BalanceLog> list = balanceLogService.list(request);
        return CommonResult.success(CommonPage.restPage(list));
    }

    @ApiOperation("用户资金明细下载")
    @RequestMapping(value = "/down", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<String> down(BalanceLogQueryRequest request) {
        request.setPageSize(999999);
        request.setPageNum(1);
        request.setUserId(AdminUserUtil.getUserId().intValue());
        Page<BalanceLog> list = balanceLogService.list(request);
        List<BalanceLog> records = list.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            List<UmsBalanceLogExport> UmsBalanceLogExports = records.stream().map(x -> {
                UmsBalanceLogExport userRechargeExport = new UmsBalanceLogExport();
                BeanUtil.copy(x, userRechargeExport);
                userRechargeExport.setType(x.getType().getDesc());
                userRechargeExport.setBalanceType(x.getBalanceType().getDesc());

                if (StringUtils.isNotEmpty(x.getDetails())) {
                    Map<String, String> resultMap = GsonUtil.convertJsonStringToHashMap(x.getDetails());


                    if (resultMap.get("寄件")!=null) {
                        userRechargeExport.setJj(resultMap.get("寄件").toString());
                    }
                    if (resultMap.get("保证金")!=null) {
                        userRechargeExport.setBzj(resultMap.get("保证金").toString());
                    }
                    if (resultMap.get("保证金释放")!=null) {
                        userRechargeExport.setSf(resultMap.get("保证金释放").toString());
                    }
                }
                SimpleUser user = x.getUser();
                if (user != null) {
                    userRechargeExport.setEmail(user.getEmail());
                }
                return userRechargeExport;

            }).collect(Collectors.toList());

            String s = staticController.exports(UmsBalanceLogExports, UmsBalanceLogExport.class);
            return CommonResult.success(s);
        }
        return CommonResult.success();
    }

    @ApiOperation("重复退款")
    @ResponseBody
    public CommonResult<String> doubleRefund() {
        List<String> ca = new ArrayList<>(81);
        List<String> orderNos = new ArrayList<>(81);
        //未处理的两笔  202401A00006c29  202401A0000c2e0
        /*orderNos.add("202401A00006e7c");
        orderNos.add("202401A00005b73");*/
        orderNos.add("202401A0000bbc1_885e");
        orderNos.add("202401A0000eeac");
        orderNos.add("202401A0000e0f5");
        orderNos.add("202401A00005e56");
        orderNos.add("202401A0000c232");
        orderNos.add("202401A000062cf");
        orderNos.add("202401A0000fa20");
        orderNos.add("202401A00006b20");
        orderNos.add("202401A00007e89");
        orderNos.add("202401A0000dba0");
        orderNos.add("202401A0000bb26");
        orderNos.add("114-8267416-3444215_c23b");
        orderNos.add("114-6071236-3861850");
        orderNos.add("113-6380846-9321046_2869");
        orderNos.add("111-5103021-9705816_6246");
        orderNos.add("111-9525080-3428262_24ad");
        orderNos.add("111-8330775-9826642_49f2");
        orderNos.add("113-5119506-1001848_73d2");
        orderNos.add("111-0547409-5493009_0155");
        orderNos.add("111-5260701-5267462_103d");
        orderNos.add("114-1128889-1937057_c53b");
        orderNos.add("112-9061211-1573032_a866");
        orderNos.add("114-8249505-0211418_009e");
        orderNos.add("111-7049717-2217842_0ef8");
        orderNos.add("111-6273447-5614601");
        orderNos.add("114-2149994-8274654_7206");
        orderNos.add("111-9702239-6558630");
        orderNos.add("113-4593058-0836264_be60");
        orderNos.add("111-3288441-4589826_3e1b");
        orderNos.add("113-8771579-4914601_2d59");
        orderNos.add("111-5203461-2025844_8800");
        orderNos.add("112-8461603-8015431_e685");
        orderNos.add("111-8216818-8574648_0998");
        orderNos.add("114-2943145-1569002_5f33");
        orderNos.add("112-5261364-5197060_c923");
        orderNos.add("111-2926428-5169069_1273");
        orderNos.add("111-6519080-3965856_c016");
        orderNos.add("202401A0000347d");
        orderNos.add("202401A00009a5d");
        orderNos.add("202401A0000a7ed");
        orderNos.add("202401A00007f3f");
        orderNos.add("202401A0000233a");
        orderNos.add("202401A000032f6");
        orderNos.add("202401A00006307");
        orderNos.add("202401A0000219d");
        orderNos.add("202401A0000f0eb");
        orderNos.add("202401A00009abc");
        orderNos.add("202401A0000ddc1");
        orderNos.add("202401A00000d12");
        orderNos.add("202401A0000ff97");
        orderNos.add("202401A0000cf7f");
        orderNos.add("202401A00009cfd");
        orderNos.add("202401A00008166");
        orderNos.add("202401A00009caa");
        orderNos.add("202401A0000b532_eac8");
        orderNos.add("202401A0000f7e7_244d");
        orderNos.add("202401A000035ef");
        orderNos.add("202401A00005251");
        orderNos.add("202401A00009597");
        orderNos.add("202401A000049a9");
        orderNos.add("202401A0000e6dd");
        orderNos.add("202401A00006767");
        orderNos.add("202401A00000671");
        orderNos.add("202401A0000ce58");
        orderNos.add("202401A0000c474");
        orderNos.add("202401A0000197a");
        orderNos.add("202401A00007478");
        orderNos.add("202401A0000d844");
        orderNos.add("202401A0000b0a3");
        orderNos.add("202401A00004105");
        orderNos.add("202401A0000830b");
        orderNos.add("202401A00006c29");
        orderNos.add("PO-211-11033451684470522");
        orderNos.add("202405030005");
        orderNos.add("202405030004");
        orderNos.add("202405030003");
        orderNos.add("202405030002");
        orderNos.add("202405030001");
        orderNos.add("202401A0000c2e0");
        for (String orderNo : orderNos) {
            BalanceLog log = balanceLogService.lambdaQuery().eq(BalanceLog::getOrderNo, orderNo)
                    .eq(BalanceLog::getType, BalanceLogType.RECHARGE)
                    .eq(BalanceLog::getRemark,"退款多退，扣除")
                    .one();
            if (ObjectUtils.isEmpty(log)) {
                ca.add(orderNo);
            } else {
                log.setChangeValue(log.getChangeValue().multiply(new BigDecimal("-1")));
                balanceLogService.updateById(log);
            }
        }
        return CommonResult.success(JSON.toJSONString(ca));
    }

    @ApiOperation("取消订单，审核拒绝，退款bug")
    //@RequestMapping(value = "/bug2", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<String> bug2() {
        return balanceLogService.bug2();
    }
    @RequestMapping(value = "/bug3", method = RequestMethod.GET)
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> bug3() {
        List<String> aa = new ArrayList<>(13);
        List<String> orderNo = new ArrayList<>(13);
        orderNo.add("202401A0000d8f6");
        orderNo.add("202401A0000b383");
        orderNo.add("202401A00003c70");
        orderNo.add("202401A00000358");
        orderNo.add("202401A0000ea27");
        orderNo.add("202401A00004ec2");
        orderNo.add("202401A0000abc3");
        orderNo.add("202401A00008277");
        orderNo.add("202401A00004f0b");
        orderNo.add("202401A0000aa25");
        orderNo.add("202401A000083b6");
        for (String s : orderNo) {
            Order order = orderService.lambdaQuery().eq(Order::getOrderNo, s).eq(Order::getStatus, OrderStatus.CANCEL_ING).one();
            if (ObjectUtils.isEmpty(order)){
                aa.add(s);
            }else {
                orderService.lambdaUpdate()
                        .eq(Order::getOrderNo, s)
                        .eq(Order::getStatus, OrderStatus.CANCEL_ING)
                        .set(Order::getStatus, OrderStatus.CANCEL)
                        .set(Order::getEarnest, 0)
                        .update();
                //查询 支付信息
                List<BalanceLog> list = balanceLogService.lambdaQuery().eq(BalanceLog::getOrderNo, s).list();
                if (CollectionUtil.isEmpty(list)){
                    aa.add(s);
                }else {
                    UmsAdmin umsAdmin = umsAdminService.getById(order.getUserId());
                    if (ObjectUtils.isEmpty(umsAdmin)){
                        aa.add(s);
                    }else {
                        umsAdminService.lambdaUpdate().eq(UmsAdmin::getId,order.getUserId())
                                .setSql("balance = balance  + " + order.getEarnest().add(order.getRate()))
                                .setSql("earnest_balance = earnest_balance - " + order.getEarnest())
                                .update();
                        //生成金额记录
                        BalanceLog newBa = new BalanceLog();
                        newBa.setUserId(order.getUserId());
                        newBa.setChangeValue(order.getEarnest().add(order.getRate()));
                        newBa.setAfterValue(umsAdmin.getBalance().add(order.getEarnest().add(order.getRate())));
                        newBa.setBalanceType(BalanceType.BALANCE);
                        newBa.setOrderNo(s);
                        newBa.setRemark("退款");
                        newBa.setType(BalanceLogType.REFUND);
                        newBa.setSellerId(order.getSellerId());
                        List<BalanceLog.Detail> details = new ArrayList<>();
                        details.add(new BalanceLog.Detail("寄件", order.getRate().toString()));
                        details.add(new BalanceLog.Detail("保证金释放", order.getEarnest().toString()));
                        newBa.setDetails(new Gson().toJson(details));
                        balanceLogService.save(newBa);
                    }
                }
            }
        }
        return CommonResult.success(JSON.toJSONString(aa));
    }
}

